package com.wyvoid.forum.util;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

import com.wyvoid.forum.domain.Settings;
import com.wyvoid.forum.domain.Forum;
import com.wyvoid.forum.service.ISettingsService;
import com.wyvoid.forum.service.IForumService;

/**
 * <p>51void.com</p>
 * User:cjp
 * Date: 2007-5-13
 * Time: 20:19:27
 */
public class ForumUtil {
    public static ServletContext application;
    public static WebApplicationContext context;
    public static Map settings;
    public static List<Forum> forums;

    public static final String HIGHESTTOTALCOUNTER = "highestTotalCounter";
    public static final String HIGNESTTOTALCOUNTERTIME = "hignestTotalCounterTime";


    public static void putSettingsAndToDB(String key, String value) {
        settings.put(key, value);
        Settings settings = new Settings(key, value);
        ISettingsService settingsService = (ISettingsService) ForumUtil.context.getBean("settingsService");
        settingsService.updateSettings(settings);
    }

    public static void init(ServletContext app) {
        application=app;
        context= WebApplicationContextUtils.getWebApplicationContext(application);
        ISettingsService settingsService = (ISettingsService) context.getBean("settingsService");
        Map<String, String> settingsMap = new HashMap<String, String>();
        List<Settings> settingsList = settingsService.getSettings();
        for (Settings settings : settingsList) {
            settingsMap.put(settings.getVariable(), settings.getValue());
        }

        IForumService forumService= (IForumService) context.getBean("forumService");
        forums=forumService.getForums();
        application.setAttribute("settings", settingsMap);
        application.setAttribute("forums", forums);
        settings = settingsMap;
    }
}
